/**
 * Created by goldbillka on 25.11.13.
 */

function TodoCtrl($scope) {
    $scope.todos = [
        {text:'Работа', done:true, percent:80},
        {text:'Отдых', done:false, percent:20}];

    $scope.addProject = function() {
        $scope.todos.push({text:$scope.todoText, percent:$scope.todoPercent,done:false});
        $scope.todoText = '';
        $scope.todoPercent = '';
    };

    $scope.remaining = function() {
        var count = 0;
        angular.forEach($scope.todos, function(todo) {
            count += todo.done ? 0 : 1;
        });
        return count;
    };

    $scope.archive = function() {
        var oldTodos = $scope.todos;
        $scope.todos = [];
        angular.forEach(oldTodos, function(todo) {
            if (!todo.done) $scope.todos.push(todo);
        });
    };
}


function Ctrl2($scope,$timeout) {
    $scope.format = 'M/d/yy h:mm:ss a';
    $scope.blood_1 = 100;
    $scope.blood_2 = 120;

    var stop;
    $scope.fight = function() {
        stop = $timeout(function() {
            if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
                $scope.blood_1 = $scope.blood_1 - 3;
                $scope.blood_2 = $scope.blood_2 - 4;
                $scope.fight();
            } else {
                $timeout.cancel(stop);
            }
        }, 100);
    };

    $scope.stopFight = function() {
        $timeout.cancel(stop);
    };

    $scope.resetFight = function() {
        $scope.blood_1 = 100;
        $scope.blood_2 = 120;
    }


    $scope.when  = function( booleanExpr, trueValue, falseValue) {
        return booleanExpr ? trueValue : falseValue;
    };


    var isPaused  = false,
        pause = function() {
            isPaused = true;
        },
        resume = function() {
            isPaused = false;
            runCounter();
        },
        runCounter = function() {
            if ( isPaused ) return;

            $scope.countDown -= 1;
            if ( $scope.countDown > 0)
                $timeout(runCounter, 1000);
        },
        toggleCounter = function() {
            isPaused = !isPaused;
            runCounter();
        };

    debugger;

    $scope.countDown = 15;

    $scope.pause     = pause;
    $scope.resume    = resume;
    $scope.isPaused  = function() {
        return isPaused;
    };
    $scope.onToggleCounter = toggleCounter;
    runCounter();
}

angular.module('time', [])
    // Register the 'myCurrentTime' directive factory method.
    // We inject $timeout and dateFilter service since the factory method is DI.
    .directive('myCurrentTime', function($timeout, dateFilter) {
        // return the directive link function. (compile function not needed)
        return function(scope, element, attrs) {
            var format,  // date format
                timeoutId; // timeoutId, so that we can cancel the time updates

            // used to update the UI
            function updateTime() {
                element.text(dateFilter(new Date(), format));
            }

            // watch the expression, and update the UI on change.
            scope.$watch(attrs.myCurrentTime, function(value) {
                format = value;
                updateTime();
            });

            // schedule update in one second
            function updateLater() {
                // save the timeoutId for canceling
                timeoutId = $timeout(function() {
                    updateTime(); // update DOM
                    updateLater(); // schedule another update
                }, 1000);
            }

            // listen on DOM destroy (removal) event, and cancel the next UI update
            // to prevent updating time ofter the DOM element was removed.
            element.bind('$destroy', function() {
                $timeout.cancel(timeoutId);
            });

            updateLater(); // kick off the UI update process.


            // Provide ternary like support for controller...

        }
    });


angular.module('timer', [])
    .directive('timer', ['$compile', function ($compile) {
        return  {
            restrict: 'E',
            replace: false,
            scope: {
                interval: '=interval',
                startTimeAttr: '=startTime',
                countdownattr: '=countdown',
                autoStart: '&autoStart'
            },
            controller: ['$scope', '$element', '$attrs', function ($scope, $element, $attrs) {
                //angular 1.2 doesn't support attributes ending in "-start", so we're
                //supporting both "autostart" and "auto-start" as a solution for
                //backward and forward compatibility.
                $scope.autoStart = $attrs.autoStart || $attrs.autostart;

                if ($element.html().trim().length === 0) {
                    $element.append($compile('<span>{{millis}}</span>')($scope));
                }

                $scope.startTime = null;
                $scope.timeoutId = null;
                $scope.countdown = $scope.countdownattr && parseInt($scope.countdownattr, 10) >= 0 ? parseInt($scope.countdownattr, 10) : undefined;
                $scope.isRunning = false;

                $scope.$on('timer-start', function () {
                    $scope.start();
                });

                $scope.$on('timer-resume', function () {
                    $scope.resume();
                });

                $scope.$on('timer-stop', function () {
                    $scope.stop();
                });

                function resetTimeout() {
                    if ($scope.timeoutId) {
                        clearTimeout($scope.timeoutId);
                    }
                }

                $scope.start = $element[0].start = function () {
                    $scope.startTime = $scope.startTimeAttr ? new Date($scope.startTimeAttr) : new Date();
                    $scope.countdown = $scope.countdownattr && parseInt($scope.countdownattr, 10) > 0 ? parseInt($scope.countdownattr, 10) : undefined;
                    resetTimeout();
                    tick();
                };

                $scope.resume = $element[0].resume = function () {
                    resetTimeout();
                    if ($scope.countdownattr) {
                        $scope.countdown += 1;
                    }
                    $scope.startTime = new Date() - ($scope.stoppedTime - $scope.startTime);
                    tick();
                };

                $scope.stop = $scope.pause = $element[0].stop = $element[0].pause = function () {
                    $scope.stoppedTime = new Date();
                    resetTimeout();
                    $scope.$emit('timer-stopped', {millis: $scope.millis, seconds: $scope.seconds, minutes: $scope.minutes, hours: $scope.hours, days: $scope.days});
                    $scope.timeoutId = null;
                };

                $element.bind('$destroy', function () {
                    resetTimeout();
                });

                function calculateTimeUnits() {
                    $scope.seconds = Math.floor(($scope.millis / 1000) % 60);
                    $scope.minutes = Math.floor((($scope.millis / (60000)) % 60));
                    $scope.hours = Math.floor((($scope.millis / (3600000)) % 24));
                    $scope.days = Math.floor((($scope.millis / (3600000)) / 24));
                }

                //determine initial values of time units
                if ($scope.countdownattr) {
                    $scope.millis = $scope.countdownattr * 1000;
                } else {
                    $scope.millis = 0;
                }
                calculateTimeUnits();

                var tick = function () {

                    $scope.millis = new Date() - $scope.startTime;
                    var adjustment = $scope.millis % 1000;

                    if ($scope.countdownattr) {
                        $scope.millis = $scope.countdown * 1000;
                    }

                    calculateTimeUnits();
                    if ($scope.countdown > 0) {
                        $scope.countdown--;
                    }
                    else if ($scope.countdown <= 0) {
                        $scope.stop();
                        return;
                    }

                    //We are not using $timeout for a reason. Please read here - https://github.com/siddii/angular-timer/pull/5
                    $scope.timeoutId = setTimeout(function () {
                        tick();
                        $scope.$digest();
                    }, $scope.interval - adjustment);

                    $scope.$emit('timer-tick', {timeoutId: $scope.timeoutId, millis: $scope.millis});
                };

                if ($scope.autoStart === undefined || $scope.autoStart === true) {
                    $scope.start();
                }
            }]
        };
    }]);